﻿using ExcelParser.Reader;
using ExcelParser.Writer;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace ExcelParser
{
    public class ConfigParser
    {
        public static Action<string> Logger;
        public static Action<string> ErrorLogger;

        public string Namespace { get; set; }

        public ConfigParser()
        {
            Namespace = "Config";
        }

        public void StartParse(string configDirectory, string outputDll, string serializeDirectory, string unityEngineDllPath)
        {
            ExcelReader reader = new ExcelReader(configDirectory, serializeDirectory, Namespace);
            List<ExcelSheet> sheets = reader.LoadExcels();

            CodeGen.CodeGenerator<CSharpWriter> generator = new CodeGen.CodeGenerator<CSharpWriter>(configDirectory, outputDll);
            generator.GenCode(sheets);

            List<string> otherCodes = new List<string>
            {
                generator.GenConfigManager(sheets, Namespace)
            };
            if (generator.Compile(sheets, otherCodes, unityEngineDllPath, out AppDomain excelDomain, out Assembly excelAssembly))
            {
                reader.ReadExcel(excelAssembly, sheets);
            }

            AppDomain.Unload(excelDomain);

            foreach (var code in otherCodes)
            {
                Logger?.Invoke(code);
            }
        }
    }
}
